<?php
namespace hema\delivery\engine;

use think\facade\Cache;
use hema\Http;
/**
 * 闪送
*/
class Shansong extends Basics
{
	/**
     * 预发布订单 - 计算订单价格
	*/
	public function preOrder($data)
	{
	    $params = $this->params($data);
		$url = $this->config['api_url'] . '/openapi/developer/v5/orderCalculate';
        $result = json_decode(Http::post($url, $params),true);
        if($result['status'] == 200) {
            if($result['data']['estimateReceiveSecond'] == -1){
                $delivery_time = '无预计时长';
            }else{
                $delivery_time = '预计' . (int)$result['data']['estimateReceiveSecond']/60 . '分钟';
            }
            return [
				'delivery_time' => $delivery_time, //预计送达时间
				'delivery_distance' => $result['data']['totalDistance'] . '米', //配送距离
				'delivery_price' => '￥' . $result['data']['totalFeeAfterSave'] / 100 . '元', //配送费用
				'time' => '', //预计送达时间
				'distance' => $result['data']['totalDistance'], //配送距离
				'price' => $result['data']['totalFeeAfterSave'] / 100, //配送费用
				'shansong' => $result['data']
			];
        }
        $this->error = $result['msg'];
		return false;
	}
	
	/**
     * 发布订单
	*/
	public function addOrder($data)
	{
		$params = $this->params($data);
		$url = $this->config['api_url'] . '/openapi/developer/v5/orderPlace';
        $result = json_decode(Http::post($url, $params),true);
        if($result['status'] == 200) {
            return $result['data'];
        }
        $this->error = $result['msg'];
		return false;
	}

	/**
     * 取消订单
	*/
	public function cancelOrder($order_no)
	{
		$params = $this->params([
		    'issOrderNo' => $order_no
		]);
		$url = $this->config['api_url'] . '/openapi/developer/v5/abortOrder';
        $result = json_decode(Http::post($url, $params),true);
        if($result['status'] == 200) {
            return $result['data'];
        }
        $this->error = $result['msg'];
		return false;
	}	

	/**
	* 公共参数
	*/
	private function params($data = null, $token = true){
	    $params = [
	        'clientId' => $this->config['app_key'],
			'timestamp' => time()
	    ];
	    if($token){
	        $params['accessToken'] = $this->getToken();
	    }
		if(!is_null($data)){
			$params['data'] = hema_json($data);
		}
		$params['sign'] = $this->sign($params);
		return $params;
	}

	// 生成签名
	private function sign($params) 
	{
		$string =	$this->config['app_key'];
		if(isset($params['accessToken'])){
			$string .= 'accessToken' . $params['accessToken'];
		}
		$string .= 'clientId' . $params['clientId'];
		if(isset($params['data'])){
			$string .= 'data' . $params['data'];
		}
		$string .= 'timestamp' . $params['timestamp'];
		$string = md5($string);//MD5(32位)加密
		$sign = strtoupper($string);//字母转换为大写
		return $sign;
	}
    //获取AccessToken
	private function getToken()
	{
		if($token = Cache::get('shansong_token')){
		    return $token;
		}
		return $this->refreshToken();
	}	
    //刷新AccessToken
	private function refreshToken() 
	{
	    $params = $this->params([
	         'refreshToken' => $this->config['refresh_token']
	    ],false);
		$url = $this->config['api_url'] . '/openapi/oauth/refresh_token';
        $result = json_decode(Http::post($url, $params),true);
        if($result['status'] != 200) {
            return $this->renderError('刷新AccessToken失败');
        }
        Cache::set('shansong_token', $result['data']['access_token'], $result['data']['expires_in']);
        return $result['data']['access_token'];
	}	
}
